//
//  PayPwdViewController.m
//  DaDaBao
//
//  Created by admin on 15/8/19.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "PayPwdViewController.h"
#import "CustomTextField.h"

@interface PayPwdViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSArray *dataArr;
@property(nonatomic,copy)NSMutableString *userName;
@property(nonatomic,strong)CustomTextField *pwdText;
@property(nonatomic,strong)UITextField *oldPwdText;
@property(nonatomic,strong)UITextField *surePwdText;
@property(nonatomic,strong)UIButton *verifiCodeBtn;
@property (nonatomic,strong) NSTimer     * timer;
@property (nonatomic,assign) int           statusInt;//计数

@end

@implementation PayPwdViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登录失败，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
#pragma mark ----------------alertDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [AppGlobalClass exitLogin];
    
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    [self presentViewController:loginViewCon animated:TRUE completion:^{}];
    
    NSArray *listArray = self.navigationController.viewControllers;
    
    id tabBar = [listArray objectAtIndex:1];
    if([[tabBar class] isSubclassOfClass:[UITabBarController class]])
    {
        UITabBarController *tabBarCon = tabBar;
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:1] animated:TRUE];
    }
    else
    {
        UITabBarController *tabBarCon = [listArray objectAtIndex:2];
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:2] animated:TRUE];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    if (!_dataArr) {
        _dataArr = @[@"",@"",@"确认支付密码"];
    }

    _statusInt = 60;
    _userName = [NSMutableString stringWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"]];
    [_userName replaceCharactersInRange:NSMakeRange(3, 6) withString:@"******"];
    [self createUI];
}
-(void)createUI
{
    TopView *topView =[[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:([[[NSUserDefaults standardUserDefaults] objectForKey:@"payPasswordVStatus"]isEqualToNumber:[NSNumber  numberWithInt:1]]) ? @"修改支付密码 " :@"设置支付密码 "];
    [self.view addSubview:topView];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 64.0f+35.0f, SCREEN_WIDTH, 44.0f*3) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.bounces = FALSE;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableview];
    }
    
//  确认修改按钮
    UIButton *checkBtn =  [UIButton buttonWithType:UIButtonTypeCustom];
    checkBtn.frame = CGRectMake(15.0f, _tableview.frame.origin.y+_tableview.frame.size.height+25.0f, SCREEN_WIDTH-30.0f, 35.0f*HSCALE);
    [checkBtn setBackgroundColor:[UIColor hexStringToColor:RED_COLOR_VALUE]];
    [checkBtn setTitle:@"确认修改" forState:UIControlStateNormal];
    checkBtn.layer.cornerRadius = 5.0f;
    [checkBtn addTarget:self action:@selector(buttonCheckTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkBtn];

}

#pragma mark- tableViewDatasource &delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 43.5f, SCREEN_WIDTH, 0.5f)];
        sepLab.backgroundColor = [UIColor lightGrayColor];
        [cell addSubview:sepLab];
        
    }
    cell.textLabel.text = [_dataArr objectAtIndex:indexPath.row];
    NSString *str = @"6位数字";
    switch (indexPath.row) {
        case 0:
        {
            _verifiCodeBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 10.0f, 90, 24.0f)];
            _verifiCodeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            _verifiCodeBtn.layer.cornerRadius = 2.0f;
            _verifiCodeBtn.layer.borderWidth = 1.0f;
            _verifiCodeBtn.layer.borderColor = [[UIColor hexStringToColor:RED_COLOR_VALUE] CGColor];
            [_verifiCodeBtn setTitle:@"获取验证码 " forState:UIControlStateNormal];
            [_verifiCodeBtn setTitleColor:[UIColor hexStringToColor:RED_COLOR_VALUE] forState:UIControlStateNormal];
            [_verifiCodeBtn addTarget:self action:@selector(buttonGetTheCodeTapped:) forControlEvents:UIControlEventTouchUpInside];
            _verifiCodeBtn.hidden = ([[[NSUserDefaults standardUserDefaults] objectForKey:@"payPasswordVStatus"]isEqualToNumber:[NSNumber  numberWithInt:1]]) ? TRUE : FALSE;
            [cell addSubview:_verifiCodeBtn];
            
            //判断状态
            
            CGFloat positionValue = ([[[NSUserDefaults standardUserDefaults] objectForKey:@"payPasswordVStatus"]isEqualToNumber:[NSNumber  numberWithInt:1]]) ? 120.0f : 110.0f;
            
            _oldPwdText = [[CustomTextField alloc] initWithFrame:CGRectMake(positionValue, 13.0f, SCREEN_WIDTH-positionValue, 24.0f)];
            _oldPwdText.placeholder = ([[[NSUserDefaults standardUserDefaults] objectForKey:@"payPasswordVStatus"]isEqualToNumber:[NSNumber  numberWithInt:1]]) ? @"原支付密码 ":[NSString stringWithFormat:@"请输入%@收到的验证码",_userName] ;
            _oldPwdText.secureTextEntry = TRUE;
            [_oldPwdText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
            [cell addSubview:_oldPwdText];
            cell.textLabel.text = ([[[NSUserDefaults standardUserDefaults] objectForKey:@"payPasswordVStatus"]isEqualToNumber:[NSNumber  numberWithInt:1]]) ? @"原支付密码 ":[NSString stringWithFormat:@""] ;

        }
            break;
        case 1:
        {
             CGFloat positionValue = ([[[NSUserDefaults standardUserDefaults] objectForKey:@"payPasswordVStatus"]isEqualToNumber:[NSNumber  numberWithInt:1]]) ? 120.0f : 135.0f;
            cell.textLabel.text = ([[[NSUserDefaults standardUserDefaults] objectForKey:@"payPasswordVStatus"]isEqualToNumber:[NSNumber  numberWithInt:1]]) ? @"新支付密码 ":[NSString stringWithFormat:@"设置支付密码"] ;
            _pwdText = [[CustomTextField alloc] initWithFrame:CGRectMake(positionValue, 13.0f, SCREEN_WIDTH-positionValue, 24.0f)];
            _pwdText.placeholder = str;
            _pwdText.secureTextEntry = TRUE;
            _pwdText.keyboardType = UIKeyboardTypeNumberPad;

            [_pwdText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
            
            [cell addSubview:_pwdText];
        }
            break;
        case 2:
        {
            _surePwdText = [[CustomTextField alloc] initWithFrame:CGRectMake(135.0f, 13.0f, SCREEN_WIDTH-135.0f, 24.0f)];
            _surePwdText.keyboardType = UIKeyboardTypeNumberPad;
            _surePwdText.placeholder = str;
            _surePwdText.secureTextEntry = TRUE;
            [_surePwdText setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];

            [cell addSubview:_surePwdText];
            
        }
            break;
            
        default:
            break;
    }
    
    return cell;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark- 确认修改方法
-(void)buttonCheckTapped:(id)sender
{
    [self.view endEditing:TRUE];

//    判断新密码
    BOOL isPwdRight = [_pwdText checkNewPayPwd:_pwdText.text];
    BOOL isSurePwd = [_surePwdText.text isEqualToString:_pwdText.text];
    
   
    if (_oldPwdText.text.length >0)
    {
        if (isPwdRight == FALSE)
        {
            ALERT_VIEW(@"请输入六位数的新密码");
        }
        else
        {
            if (isSurePwd == FALSE)
            {
                ALERT_VIEW(@"两次输入的密码不相同");
            }
            else
            {
//                发送请求
                if([[[NSUserDefaults standardUserDefaults]objectForKey:@"payPasswordVStatus"] isEqualToNumber:[NSNumber numberWithInt:1]])//修改支付密码
                {
                    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

                    NSDictionary *dict = @{ @"payPassword":[AppGlobalClass md5:_pwdText.text],@"oldPayPassword": [AppGlobalClass md5:_oldPwdText.text],
                                            @"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]};
                    [AppGlobalClass PostDataWithNSstring:UPDATE_PAYPASSWORD_URL withDictionary:dict success:^(NSDictionary *dictionary){
                        
                        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
                        {
                            [self.navigationController popViewControllerAnimated:TRUE];
                            ALERT_VIEW(@"修改成功");
                        }
                        else
                        {
                            ALERT_VIEW([dictionary objectForKey:@"message"]);
                        }
                        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

                    } failure:^(NSError *error){
                        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
} networkerror:^(NSString *networkerror){
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}];
                }
                else
                {
                    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

                    NSDictionary *dict = @{ @"payPassword" : [AppGlobalClass md5:_pwdText.text], @"mobile":[[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"],
                                            @"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"], @"checkCode":_oldPwdText.text};
                    [AppGlobalClass PostDataWithNSstring:SET_PAYPASSWORD_URL withDictionary:dict success:^(NSDictionary *dictionary){ //设置支付密码
                        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
                        {
                            [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInt:1] forKey:@"payPasswordVStatus"];
                            [self.navigationController popViewControllerAnimated:TRUE];
                            ALERT_VIEW(@"设置成功");
                        }

                        else
                        {
                            ALERT_VIEW([dictionary objectForKey:@"message"]);
                        }
                        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

                    } failure:^(NSError *error){
                        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
} networkerror:^(NSString *networkerror){
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}];
                }
            }
        }
    }
    else{
        ALERT_VIEW(([[[NSUserDefaults standardUserDefaults]objectForKey:@"payPasswordVStatus"] isEqualToNumber:[NSNumber numberWithInt:1]]) ? @"原密码不能为空":@"验证码不能为空");
       
    }
    
}
#pragma mark -------------获取验证码按钮方法
-(void)buttonGetTheCodeTapped:(id)sender
{
    
    UIButton * codeBtn  = (UIButton *)sender;
    codeBtn.enabled = FALSE;
    if (!_timer)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCounting) userInfo:nil repeats:TRUE];
        [_timer fire];
    }
    
    NSDictionary *dict = @{@"mobileNumber" : [[NSUserDefaults standardUserDefaults]objectForKey:@"userCd"]};
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

    [AppGlobalClass PostDataWithNSstring:SEND_CHECKCODE_URL withDictionary:dict success:^(NSDictionary *dictionary){
        [MBProgressHUD hideHUDForView:self.view animated:TRUE];

    } failure:^(NSError *error){
        [MBProgressHUD hideHUDForView:self.view animated:TRUE];
} networkerror:^(NSString *networkerror){
    [MBProgressHUD hideHUDForView:self.view animated:TRUE];
}];
}
//时间倒计时
-(void)timeCounting
{
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    if ([phoneVersion doubleValue] > 8.0) {
        [_verifiCodeBtn setTitle:[NSString stringWithFormat:@"%d秒后重试",_statusInt] forState:UIControlStateNormal];
    }
    else{
        _verifiCodeBtn.titleLabel.frame =CGRectMake(0, 0, _verifiCodeBtn.frame.size.width, _verifiCodeBtn.frame.size.height);
        _verifiCodeBtn.titleLabel.text = [NSString stringWithFormat:@"%d秒后重试",_statusInt] ;
    }
    
    if(_statusInt == 0)
    {
        
        if ([phoneVersion doubleValue] > 8.0)
        {
            [_verifiCodeBtn setTitle:@" 重新获取 " forState:UIControlStateNormal];
        }
        else
        {
            _verifiCodeBtn.titleLabel.frame =CGRectMake(0, 0, _verifiCodeBtn.frame.size.width, _verifiCodeBtn.frame.size.height);
            _verifiCodeBtn.titleLabel.text = @" 重新获取 " ;
        }

        _statusInt = 60;
        _verifiCodeBtn.enabled = TRUE;
        [_timer invalidate];
        _timer = nil;
    }
    _statusInt -=1;
}

#pragma mark-返回上一页
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:TRUE];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [_timer invalidate];
    _timer = nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
